package com.famnote.randomchat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings.Secure;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class HomeActivity extends Activity implements OnClickListener {

	// Debugging
    private static final String TAG = "HomeActivity";
    private static final boolean D = true;
    
    
	private Activity activity;
	
	private Handler mHandler = new Handler();
	
	private ProgressDialog dialog;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);
		
		activity = this;
		
		/*
		Button btn = (Button)findViewById(R.id.random_chatting);
		btn.setOnClickListener(this);
		
		btn = (Button)findViewById(R.id.group_chatting);
		btn.setOnClickListener(this);
		*/
		
		ImageView imgView = (ImageView) findViewById(R.id.random_chatting);
		imgView.setOnClickListener(new OnClickListener() {
		    public void onClick(View v) {
		       // your code here
		    	
		    	
		    	Intent i = new Intent(activity, Chat.class);
	        	
	        	//i.putExtra("username", mUserName);
	        	
	        	startActivity(i);
	        	
		    	
		    	/*
		    	final Dialog dialog = new Dialog(activity);
		        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		        dialog.setContentView(R.layout.popup);
		        dialog.setCancelable(true);

		        WebView webView = (WebView) dialog.findViewById(R.id.webview);
		        webView.getSettings().setJavaScriptEnabled(true);
		        //webView.loadUrl("http://en.wikipedia.org/wiki/" + name.getText().toString());
		        webView.loadUrl("http://en.wikipedia.org/wiki/" + "gold");
		        webView.setWebViewClient(new WebViewClientClass());
		        */
	        	
	        	
		        /*
		        RelativeLayout btn = (RelativeLayout) dialog.findViewById(R.id.close);
		        btn.setOnClickListener(new View.OnClickListener() {
		            public void onClick(View v) {
		                dialog.dismiss();
		                        }
		            });
		            */
		            
		        //dialog.show();
		    	
		    	
		    	
		    }
		});

		imgView = (ImageView) findViewById(R.id.group_chatting);
		imgView.setOnClickListener(new OnClickListener() {
		    public void onClick(View v) {
		       // your code here
		    	
		    	String msg = getResources().getString(R.string.loading);	
		        dialog = ProgressDialog.show(activity, "", msg, true);

		        // Creating a new non-ui thread task to download xml data 
		        CheckNickNameTask checkNickNameTask = new CheckNickNameTask();

		        /*
		        String androidid = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
		        String url = "http://push.appaas.com/hulbox/of_check_nickname.php?deviceid=" + androidid;
		        */
		        
		        TelephonyManager tm = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);
		        String deviceid = tm.getDeviceId();
		        String url = "http://push.appaas.com/hulbox/rc_check_nickname.php?deviceid=" + deviceid;
		        
		        // Starting the download process
		        checkNickNameTask.execute(url);
		    	
				/*
		    	// custom dialog
				final Dialog dialog = new Dialog(activity);
				dialog.setContentView(R.layout.popup2);
				dialog.setTitle("Title...");
	 
				// set the custom dialog components - text, image and button
				TextView text = (TextView) dialog.findViewById(R.id.text);
				text.setText("Android custom dialog example!");
				ImageView image = (ImageView) dialog.findViewById(R.id.image);
				image.setImageResource(R.drawable.ic_launcher);
	 
				Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
				// if button is clicked, close the custom dialog
				dialogButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						dialog.dismiss();
					}
				});
	 
				dialog.show();
		    	*/
		    	
		    	
		    	/*
		    	LayoutInflater layoutInflater = (LayoutInflater) activity.getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
		    	View popupView = layoutInflater.inflate(R.layout.popup, null);

		    	
		    	final PopupWindow popupWindow = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		    	 
		    	popupWindow.showAsDropDown(v, 0, 0);
		    	//popupWindow.showAsDropDown(v, 0, (int)v.getTop());
		    	//popupWindow.showAtLocation(v, Gravity.LEFT, 0, 0);
		    	
		    	
		    	WebView webView = (WebView) popupView.findViewById(R.id.webview);
		         
		    	webView.getSettings().setJavaScriptEnabled(true); 
		        webView.loadUrl("http://push.appaas.com/directory/www");
		    	//webView.loadUrl("http://blog.naver.com/famnote");
		        webView.setWebViewClient(new WebViewClientClass());
				*/
		    	
		    	/*
		    	final Dialog dialog = new Dialog(activity);
		        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		        
		        dialog.setContentView(R.layout.popup);
		        
		        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
		        //dialog.getWindow().setBackgroundDrawable(null);
		        
		        //Dialog dialog = new Dialog(activity, android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
		        
		        dialog.setCancelable(true);

		        WebView webView = (WebView) dialog.findViewById(R.id.webview);
		        webView.getSettings().setJavaScriptEnabled(true);
		        //webView.loadUrl("http://en.wikipedia.org/wiki/" + name.getText().toString());
		        //webView.loadUrl("http://en.wikipedia.org/wiki/" + "gold");
		        webView.loadUrl("http://blog.naver.com/swingfish");
		        webView.setWebViewClient(new WebViewClientClass());
		        */
		        
		        //RelativeLayout btn = (RelativeLayout) dialog.findViewById(R.id.close);
		        //btn.setOnClickListener(new View.OnClickListener() {
		         //   public void onClick(View v) {
		         //       dialog.dismiss();
		         //               }
		        //    });
		           
		        //dialog.show();
				

		    }
		});
		
		
		imgView = (ImageView) findViewById(R.id.blog);
		imgView.setOnClickListener(new OnClickListener() {
		    public void onClick(View v) {
		       // your code here
		    
				Intent i = new Intent(activity, WebViewActivity.class);
	        	startActivity(i);
		    }
		});
		
		
		String msg = getResources().getString(R.string.connecting_to_server);
        dialog = ProgressDialog.show(this, "", msg, true);
        
        /*
        String androidid = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
        String url = "http://push.appaas.com/hulbox/of_popup.php?deviceid=" + androidid;
        */
        
        TelephonyManager tm = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);
        String deviceid = tm.getDeviceId();
        String url = "http://push.appaas.com/hulbox/rc_popup.php?deviceid=" + deviceid;
        
        PopupTask popupTask = new PopupTask();
        popupTask.execute(url);


		
	}
	
    private class WebViewClientClass extends WebViewClient { 
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) { 
            view.loadUrl(url); 
            return true; 
        } 
    }
	
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//getMenuInflater().inflate(R.menu.activity_home, menu);
		return true;
	}

	public void onClick(View v) 
	{
	  
	  switch(v.getId()){
	  
	  /*
	  case R.id.cancel:
	   Intent i = new Intent(getBaseContext(), LoginActivity.class);
	   startActivity(i);
	   //finish();
	   break;
	   */
	  
	  	case R.id.random_chatting:
			
	  		Intent i = new Intent(this, Chat.class);
        	
        	//i.putExtra("username", mUserName);
        	
        	startActivity(i);
		  
	  		break;
		  
	  	case R.id.group_chatting:
			
	  		/*
	        String msg = getResources().getString(R.string.loading);	
	        dialog = ProgressDialog.show(this, "", msg, true);

	        // Creating a new non-ui thread task to download xml data 
	        CheckNickNameTask checkNickNameTask = new CheckNickNameTask();

	        String androidid = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
	        
	        String url = "http://push.appaas.com/hulbox/of_check_nickname.php?deviceid=" + androidid;
	        // Starting the download process
	        checkNickNameTask.execute(url);
	  		*/
			  
			break;
	  }
	  
	  
	  
	}
	
	
	
	

    private class PopupTask extends AsyncTask<String, Integer, String>{
        String data = null;
                
        @Override
        protected String doInBackground(String... url) {
                        try{
                            data = downloadUrl(url[0]);
                                
                        }catch(Exception e){
                        	Log.d("Background Task",e.toString());
                        }
                        if(D) Log.e(TAG, "popup_url: " + data);
                        
                        return data;
        }

        @Override
        protected void onPostExecute(String result) {
                	
             dialog.dismiss();
                	
             if ((data != null) && (data != "")) {
                	final Dialog popupDlg = new Dialog(activity);
            		popupDlg.requestWindowFeature(Window.FEATURE_NO_TITLE);
            		popupDlg.setContentView(R.layout.popup);
            		popupDlg.setCancelable(true);

                    WebView webView = (WebView) popupDlg.findViewById(R.id.webview);
                    webView.getSettings().setJavaScriptEnabled(true);
                    //webView.loadUrl("http://en.wikipedia.org/wiki/" + name.getText().toString());
                    //webView.loadUrl("http://en.wikipedia.org/wiki/" + "gold");
                    //webView.loadUrl("http://blog.naver.com/swingfish");
                    webView.loadUrl(data);
                    webView.setWebViewClient(new WebViewClientClass());
                    
                  
                    Button button = (Button) popupDlg.findViewById(R.id.close);
                    button.setOnClickListener(new OnClickListener() {
            		    public void onClick(View v) {
            		    	popupDlg.dismiss();
            		    }
            		});
                    /*
                    ImageView imgView = (ImageView) popupDlg.findViewById(R.id.close);
            		imgView.setOnClickListener(new OnClickListener() {
            		    public void onClick(View v) {
            		    	popupDlg.dismiss();
            		    }
            		});
                    */
                    /*
                    webView.setOnClickListener(new OnClickListener() {
            		    public void onClick(View v) {
            		    	popupDlg.dismiss();
            		    }
            		});
                    */
                       
                    //dialog.show();
            		
                    
                    mHandler.post(new Runnable() {
                        public void run() {
                        	popupDlg.show();
                        }
                    });
            		
             }
                	
        }
    }
    
    
    
    
	/** AsyncTask to download xml data */
    private class CheckNickNameTask extends AsyncTask<String, Integer, String>{
        String data = null;
                
        @Override
        protected String doInBackground(String... url) {
                        try{
                            data = downloadUrl(url[0]);
                                
                        }catch(Exception e){
                        	Log.d("Background Task",e.toString());
                        }
                        if(D) Log.e(TAG, "nickname: " + data);
                        
                        return data;
        }

        @Override
        protected void onPostExecute(String result) {
                	
             dialog.dismiss();
                	
             if ((data == null) || (data == "")) {

      			Intent i = new Intent(activity, RegNickNameActivity.class);
     			startActivity(i); 
            		
             } else {
            	 
            	String nickName = data;
     			Intent i = new Intent(activity, MainActivity.class);
     			i.putExtra("nickname", nickName);
    			startActivity(i);
    			
             }
                	
        }
    }
	
	
	/** A method to download xml data from url */
    private String downloadUrl(String strUrl) throws IOException{
        String data = "";
        InputStream iStream = null;
        try{
                URL url = new URL(strUrl);
                
                // Creating an http connection to communicate with url 
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                // Connecting to url 
                urlConnection.connect();

                // Reading data from url 
                iStream = urlConnection.getInputStream();
                
                BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
                
                StringBuffer sb  = new StringBuffer();
                
                String line = "";
                while( ( line = br.readLine())  != null){
                	sb.append(line);
                }
                
                
                data = sb.toString();

                br.close();

        }catch(Exception e){
                Log.d("Exception while downloading url", e.toString());
                if(D) Log.e(TAG, e.toString());
        }finally{
                iStream.close();
        }

        return data;
    }
    
    

    
    public String returnNumber() {
        String number = null;
        String service = Context.TELEPHONY_SERVICE;
        TelephonyManager tel_manager = (TelephonyManager)this.getSystemService(service);
        int device_type = tel_manager.getPhoneType();

        /*
        switch (device_type) {
              case (TelephonyManager.PHONE_TYPE_CDMA):
                 number = tel_manager.getLine1Number();
              break;
              default:
                //return something else
                number = "nonumber";
               break;
        }
        */
        number = tel_manager.getLine1Number();
        
        if (number.substring(0,1).equals("+") == true) {
        	number = number.substring(1);
        }
        
        return number;
   }
    
    
	
}
